﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace HotelManagement
{
    public partial class LoginFRM : Form
    {
        SqlConnection Cnn = new SqlConnection(Globals.DBConnection());
        DataSet ds = new DataSet();
        SqlDataReader dr;

        public LoginFRM()
        {
            InitializeComponent();
        }

        private void Cancelbtn_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void OKBtn_Click(object sender, EventArgs e)
        {
            int us_id;
            SqlCommand LoginCheck = new SqlCommand("select us_id from Users Where us_username=@us_username AND us_password=@us_password", Cnn);
            LoginCheck.Parameters.AddWithValue("us_username",UserNameTxt.Text.Trim());
            LoginCheck.Parameters.AddWithValue("us_password",PasswordTxt.Text.Trim());
            Cnn.Open();
            dr = LoginCheck.ExecuteReader();

            if (dr.HasRows)
            {
                dr.Read();
                us_id = (int)dr[0];
                Cnn.Close();

                SqlCommand UpadteLoginData = new SqlCommand("UPDATE Users SET us_active = 1 WHERE us_id=@us_id ", Cnn);
                UpadteLoginData.Parameters.AddWithValue("@us_id", us_id);

                Cnn.Open();
                UpadteLoginData.ExecuteNonQuery();
                Cnn.Close();


                this.Visible = false;
                UserNameTxt.Text = "";
                PasswordTxt.Text = "";

                MainFRM mf = new MainFRM();
                mf.ShowDialog();


                SqlCommand UpadteLogoutData = new SqlCommand("UPDATE Users SET us_active = 0 WHERE us_id=@us_id ", Cnn);
                UpadteLogoutData.Parameters.AddWithValue("@us_id", us_id);

                Cnn.Open();
                UpadteLogoutData.ExecuteNonQuery();
                Cnn.Close();

                this.Visible = true;
                
            }
            else 
            {
                MessageBox.Show("نام کاربری یا کلمه عبور اشتباه است ");
                Cnn.Close();
            }
        }

        private void LoginFRM_Load(object sender, EventArgs e)
        {
            SqlCommand UpadteLogoutData = new SqlCommand("UPDATE Users SET us_active = 0 ", Cnn);
            

            Cnn.Open();
            UpadteLogoutData.ExecuteNonQuery();
            Cnn.Close(); 
        }

        private void LoginFRM_KeyPress(object sender, KeyPressEventArgs e)
        {
        }

        private void LoginFRM_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyValue== 13)
            {
                OKBtn_Click(this, e);
            }
        }
    }
}
